/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.application.isradeleon.notify.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Http操作
 */
public class HttpUtils {
    private static InputStream inputStream;
    private static HttpURLConnection urlConn;

    /**
     * 从url中获取流
     *
     * @param imgUrl url
     * @return stream
     */
    public static InputStream getStream(String imgUrl) {
        try {
            URL url = new URL(imgUrl);
            URLConnection tempConn = url.openConnection();
            if (tempConn instanceof HttpURLConnection) {
                urlConn = (HttpURLConnection) tempConn;
            }
            if (urlConn != null) {
                urlConn.connect();
                inputStream = urlConn.getInputStream();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 关闭流
     */
    public static void closeStream() {
        try {
            if (inputStream == null) {
                return;
            }
            inputStream.close();
            if (urlConn == null) {
                return;
            }
            urlConn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
